<?php

class FormAction_View extends FormAction
{

  protected $action = Form::ACTION_VIEW;

  public function __construct(Form $form)
  {
    parent::__construct($form);
  }

  public function execute()
  {
    $this->loadData();
  }

  public function render()
  {
    $view = $this->getView();
    $view->set('data', $this->getIterator());
    return parent::render();
  }

  protected function loadData()
  {
    foreach ((array) $this->form->getId() as $id) {
      $params = array();

      $params['fields'] = array($this->form->pk);
      $params['where'] = array();
      $params['data'] = array();

      foreach ($this->form->getFilters() as $filter) {
        $filter->injectQueryParams($params);
      }

      $elements = $this->form->getElements($this->action);
      while ($element = $elements->next()) {
        $element->injectQueryParams($params);
      }

      $params['fields'] = array_filter(array_unique($params['fields']));

      $row = $this->gateway()->find($id, $params);

      $this->filterDbData($row, $this->action);

      if (is_null($row)) {
        throw new Exception("Record not found");
      }

      $this->formData[] = &$row;
    }
  }

}
